<template>
</template>
<script>
import '@/assets/map/ol/ol.css';
import { getRESTLayer,getVectorTileLayer } from "@/map/projMap.js";
import VectorLayer from 'ol/layer/Vector';
import {Vector as VectorSource} from 'ol/source';
import GeoJSON from 'ol/format/GeoJSON';
import Overlay from 'ol/Overlay';
import Feature from 'ol/Feature';
import Point from 'ol/geom/Point';
import Polygon from 'ol/geom/Polygon';
import LineString from 'ol/geom/LineString';
import Circle from 'ol/geom/Circle';
import {Fill, Stroke, Style, Icon, Circle as CircleStyle,Text} from 'ol/style';
import {boundingExtent} from 'ol/extent';
import dingweiImg from '@/assets/map/image/newImage/blueMarker.png';
import { MapService,QueryService,QueryByDistanceParameters } from '@supermap/iclient-ol';

export default {
  name: "MapLayersMap",
  components: {

  },
  props:{
    map:{//地图对象
      type: Object,
      required:false,
      default: {}
    },
    dataTypeInfoArray:{//图层数据类型数组
      type: Array,
      required:false,
      default: []
    },
    layerInfoParams:{//查询图层数据参数
      type: Object,
      required:false,
      default: {}
    },
    clearAllLayersBool:{//是否清除全部图层
      type: Boolean,
      required:false,
      default: false
    },
    showAllLayersBool:{//是否显示全部图层
      type: Boolean,
      required:false,
      default: false
    },
    customStylesObj:{//自定义样式对象
      type: Object,
      required:false,
      default: {}
    },
  },
  emits:["getLegendHtml","finishClearAll","setSelectData","finishShowAll"],
  data() {
    return {
      restLayerArray:[],//查询图层数组
      allLayerNameArray:[],//图层名称数组
      selectLayerIndex:null,//选中图层的序号
      selectVectorLayer:null,//点选范围矢量图层
    }
  },
  watch: {
    map: {//地图对象
      handler: function(newVal,oldVal){
        if(newVal!=oldVal){
          //初始化地图图层数据组件信息
          this.initMap();
        }
      },
      immediate:true
    },
    dataTypeInfoArray:{//图层数据类型数组
      handler: function(newVal,oldVal){
        if(newVal!=oldVal){
          //初始化全部图层数据类型数组
          this.initAllRestLayers(newVal);
        }
      },
      immediate:true
    },
    layerInfoParams: {//查询图层信息参数
      handler: function(newVal,oldVal){
        if(newVal!=oldVal || newVal.code!=oldVal.code){
          //根据查询图层信息参数查询并显示图层
          this.queryLayersByParams(newVal);
        }
      },
      immediate:true
    },
    clearAllLayersBool:{//是否清除全部图层
      handler: function(newVal,oldVal){
        if(newVal){
          this.clearAllLayers();//清除全部图层
        }
      },
      immediate:true
    },
    showAllLayersBool:{//是否显示全部图层
      handler: function(newVal,oldVal){
        if(newVal){
          this.showAllLayers();//显示全部图层
        }
      },
      immediate:true
    },
    customStylesObj:{//设置自定义样式
      handler: function(newVal,oldVal){
        if(newVal){
          this.changeAllLayersCustomStyle();//更新图层自定义样式
        }
      },
      immediate:true
    },
  },
  mounted() {
    let that = this;
    //地图图层数据组件异步加载
    this.$nextTick(function(){
      //地图图层数据组件异步加载
      setTimeout(() => {
        //初始化地图图层数据组件信息
        that.initMap();
      }, 200);
    });
  },
  methods: {
    initMap() {
      if(this.map!=null && this.map.getSize()!=null){
        if(this.initBool){//是否完成初始化基础数据图层控件
          return;
        }
        let that = this;
        //弹出窗口
        this.popupInfoLayer = new Overlay({
          element: document.createElement('div'),
          positioning: 'center-center'
        });
        this.map.addOverlay(this.popupInfoLayer);
        this.popupInfoLayer.setPosition(undefined);

        //点选范围矢量图层
        this.selectVectorLayer = new VectorLayer({
          source: new VectorSource({
            wrapX: false
          }),
          projection: 'EPSG:4490'
        });
        this.map.addLayer(this.selectVectorLayer);
        this.selectVectorLayer.setZIndex(20);

        //地图点击事件
        this.map.on('click', function (e) {
          //清空全部选择图层要素
          that.clearAllSelectionLayer();
          let coordinate = that.map.getEventCoordinate(e.originalEvent);
          //点击要素事件
          that.map.forEachFeatureAtPixel(e.pixel, function (feature) {
            console.log("feature.getProperties");
            console.log(feature.getProperties());
            let attributes = feature.getProperties().attributes;
            // console.log(attributes);
            if(feature.getProperties().layerName){
              //根据图层名称获取序号
              let layerName = feature.getProperties().layerName.split("#")[0];
              let index = that.allLayerNameArray.indexOf(layerName);
              let flag = null;
              if(layerName.indexOf("czt_bridge")!=-1){//交通-桥梁czt_bridge_point、czt_bridge_line
                index = that.allLayerNameArray.indexOf("czt_bridge@fxfzczt");
                if(index==-1){
                  index = that.allLayerNameArray.indexOf("czt_bridge_line@fxfzczt");
                }
                flag = attributes["flag"];
              }
              if(index!=-1){
                //主键ID
                let fieldId = that.dataTypeInfoArray[index].fieldId;
                let id = feature.getProperties().attributes[fieldId];
                //矢量切片样式
                if(that.restLayerArray[index].vectorTileStyles){
                  that.restLayerArray[index].vectorTileStyles.featureSelectedFunction({
                    selectedId: id,
                    layerName: feature.getProperties().layerName,
                    fieldId:fieldId
                  });
                  that.selectLayerIndex = index;
                  if(that.restLayerArray[index].vectorTileLayer){
                    that.restLayerArray[index].vectorTileLayer.changed();
                  }
                }
                //数据类型
                let dataTypeName = that.dataTypeInfoArray[index].name;
                let obj = {
                  selectId:id,
                  selectType:dataTypeName,
                  flag:flag
                }
                that.$emit("setSelectData",obj);
              }
            }
            return true;
          }, {hitTolerance: 5});
        });

        //是否完成初始化基础数据图层控件
        this.initBool = true;
      }
    },
    getTextFormat(str){//格式化文本内容
      if(str==null || str==undefined){
        str = "";
      }
      return str;
    },
    getPolyonStyle(color,backgroundColor){//多边形样式
      if(backgroundColor==null){
        backgroundColor = "rgba(0,0,0,0)";
      }
      let style = new Style({
        fill:new Fill({//填充样式
          color:backgroundColor
        }),
        stroke:new Stroke({//描绘
          width:2,//宽
          color:color
        })
      });

      return style;
    },
    getPolyonTextStyle(color,backgroundColor,text){//多边形文字样式
      if(backgroundColor==null){
        backgroundColor = "rgba(0,0,0,0)";
      }
      let style = new Style({
        fill:new Fill({//填充样式
          color:backgroundColor
        }),
        stroke:new Stroke({//描绘
          width:2,//宽
          color:color
        }),
        text: new Text({
          text: text,
          fill: new Fill({
            color: 'blue'
          }),
          offsetY:0
        })
      });

      return style;
    },
    getPointStyle(){//点图标样式
      let style = new Style({
        image: new Icon({
          src: dingweiImg,
          /*anchor: [0.5, 1]*/
          anchor: [0.5, 0.8]
        }),
      });

      return style;
    },
    getPointStyleByColor(fillColor,text){//圆点样式
      let style = null;
      //显示文字
      if(this.showTextLayerBool){
        style = new Style({
          image: new CircleStyle({
            radius: 5,
            fill: new Fill({
              color: fillColor,
            }),
          }),
          text: new Text({
            text: text,
            fill: new Fill({
              color: 'black'
            }),
            stroke:new Stroke({//线
              width:2,//宽
              color:"white"
            }),
            offsetY:-10
          })
        });
      }else{
        style = new Style({
          image: new CircleStyle({
            radius: 5,
            fill: new Fill({
              color: fillColor,
            }),
          })
        });
      }

      return style;
    },
    getPointTextStyle(radius,color,str,type){//点图标文字样式
      //设定地震序号点
      let style = null;
      if(type=="设定地震"){
        style = new Style({
          image: new CircleStyle({
            radius: radius,
            stroke: new Stroke({
              color: "black",
              width: 1
            }),
            fill: new Fill({
              color: "red"
            })
          }),
          text: new Text({
            text: str,
            fill: new Fill({
              color: 'black'
            })
          })
        });
      }else if(type=="省"){
        style = new Style({
          text: new Text({
            text: str,
            fill: new Fill({
              color: 'red'
            })
          })
        });
      }else if(type=="市"){
        style = new Style({
          image: new CircleStyle({
            radius: radius,
            stroke: new Stroke({
              color: "black",
              width: 1
            }),
            fill: new Fill({
              color: "red"
            })
          }),
          text: new Text({
            text: str,
            fill: new Fill({
              color: 'black'
            })
          })
        });
      }else if(type=="区县"){
        style = new Style({
          image: new CircleStyle({
            radius: 2,
            stroke: new Stroke({
              color: "black",
              width: 1
            })
          }),
          text: new Text({
            text: str,
            fill: new Fill({
              color: 'black'
            })
          })
        });
      }else if(type=="乡镇"){
        style = new Style({
          image: new CircleStyle({
            radius: 2,
            stroke: new Stroke({
              color: "black",
              width: 1
            })
          }),
          text: new Text({
            text: str,
            fill: new Fill({
              color: 'black'
            })
          })
        });
      }

      return style;
    },
    getLineStringStyle(color,text){//线样式
      let style = null;
      //显示文字
      if(this.showTextLayerBool){
        style = new Style({
          fill:new Fill({//填充样式
            color:"rgba(0,0,0,0)"
          }),
          stroke:new Stroke({//线
            width:2,//宽
            color:color
          }),
          text: new Text({
            text: text,
            fill: new Fill({
              color: 'black'
            }),
            stroke:new Stroke({//线
              width:2,//宽
              color:"white"
            }),
            offsetY:-5
          })
        });
      }else{
        style = new Style({
          fill:new Fill({//填充样式
            color:"rgba(0,0,0,0)"
          }),
          stroke:new Stroke({//线
            width:2,//宽
            color:color
          })
        });
      }

      return style;
    },
    //处理经纬度
    getLonLat(longitude,latitude){
      let lonlat = null;
      if(longitude!=null && latitude!=null && longitude!="" && latitude!=""){
        let lon = Number(longitude);
        let lat = Number(latitude);
        if(lon>0 && lon<180 && lat>0 && lat<90){
          lonlat = [lon,lat];
        }
      }

      return lonlat;
    },
    //缩放到区域位置
    showBoundingExtent(coordinates){
      if (this.map!=null && coordinates!=null && coordinates.length > 1) {
        let extent = boundingExtent(coordinates);
        //this.map.getView().fit(extent, {duration: 1000, padding: [50, 50, 50, 50]});
        this.map.getView().fit(extent, {padding: [50, 50, 50, 50]});
      }
    },
    //REST图层查询
    createMapRestLayer(index,layerUrl,layerID,zIndex){//根据layerUrl、临时图层layerID和zIndex查询并添加瓦片地图图层REST
      debugger
      let that = this;
      //瓦片地图图层
      let mapService = new MapService(layerUrl);//根据超图REST图层获取图层信息
      mapService.getMapInfo(function (serviceResult) {
        if(serviceResult.result!=undefined){
          let mapJSONObj = serviceResult.result;
          //获取超图发布的REST图层
          //let options = TileSuperMapRest.optionsFromMapJSON(layerUrl, mapJSONObj);
          let layerName = mapJSONObj.name;//图层名称
          //获取图层范围
          let bounds = mapJSONObj.bounds;
          let left = bounds.left;
          let bottom = bounds.bottom;
          let right = bounds.right;
          let top = bounds.top;
          let origin = [left, top];//左上角
          let extent = [left, bottom, right, top];//图层范围
          //获取超图发布的REST图层（自定义比例尺）
          let layer = getRESTLayer(layerUrl,layerID,origin,extent,mapJSONObj,17);
          that.map.addLayer(layer);
          //设置图层叠加顺序
          layer.setZIndex(zIndex);
          //添加到REST图层数组
          that.restLayerArray[index].restTileLayer = layer;
          if(layerID && layerID!==""){
            //设置临时图层ID
            that.restLayerArray[index].tempLayerId = layerID;
          }
          // console.log("extent");
          // console.log(extent);
          //缩放到图层范围
          that.map.getView().fit(extent, {padding: [50, 50, 50, 50]});
          //图层范围
          let bbox = extent.join(",");
          //图层显示名称
          let realName = that.restLayerArray[index].name;
          //获取图例
          that.getLayerLegend(realName,layerUrl,bbox);//根据url获取图层图例信息
        }
      });
    },
    //临时图层SQL查询更新并获取瓦片图层REST
    deleteRestMapTempLayersSet(layerUrl,layerID){//删除超图临时图层
      let that = this;
      let url = encodeURI(layerUrl + "/tempLayersSet.rjson");
      //查询
      let httpRequest = new XMLHttpRequest();//第一步：建立所需的对象
      httpRequest.open('GET', url, true);//第二步：打开连接  将请求参数写在url中  ps:"http://localhost:8080/rest/xxx"
      httpRequest.send();//第三步：发送请求  将请求参数写在URL中
      //获取数据后的处理程序
      httpRequest.onreadystatechange = function () {
        if (httpRequest.readyState == 4 && httpRequest.status == 200) {
          let json = httpRequest.responseText;//获取到json字符串，还需解析
          let obj = JSON.parse(json);
          if(obj.length>0){
            for(let i=0;i<obj.length;i++){
              let path = obj[i].path;
              if(layerID!=null && layerID!=""){//指定临时图层ID
                if(obj[i].name==layerID){
                  that.deleteTempLayersSet(path);//删除超图临时图层
                  break;
                }
              }else{//全部临时图层
                that.deleteTempLayersSet(path);//删除超图临时图层
              }
            }
          }
        }
      };
    },
    deleteTempLayersSet(url){//删除超图临时图层
      url = encodeURI(url);
      let xhr = new XMLHttpRequest();//第一步：建立所需的对象
      xhr.open("DELETE", url, true);//第二步：打开连接  将请求参数写在url中
      xhr.send();//第三步：发送请求  将请求参数写在URL中
      // 获取数据后的处理程序
      xhr.onreadystatechange = function(){
        let readyState = xhr.readyState;
        if (readyState == 4){
          let status = xhr.status;
          let responseText =  xhr.responseText ;
          let result = JSON.parse(responseText);
          if(result.succeed){
            //that.$message({ message: '删除临时图层成功!', type: 'success' });
          }else{
            //that.$message({ message: '删除临时图层失败!', type: 'warning' });
          }
          xhr.onreadystatechange = function(){};
          xhr = null;
        }
      };
    },
    createRestMapTempLayersSet(index,layerUrl,zIndex,sqlText){//查询REST图层信息并创建新的临时图层
      let url = encodeURI(layerUrl +"/layers.rjson");
      let that = this;
      //查询REST图层信息
      let httpRequest = new XMLHttpRequest();//第一步：建立所需的对象
      httpRequest.open('GET', url, true);//第二步：打开连接  将请求参数写在url中
      httpRequest.send();//第三步：发送请求  将请求参数写在URL中
      //获取数据后的处理程序
      httpRequest.onreadystatechange = function () {
        if (httpRequest.readyState == 4 && httpRequest.status == 200) {
          let json = httpRequest.responseText;//获取到json字符串，还需解析
          let obj = JSON.parse(json);
          if(obj.length>0){
            if(sqlText!=null && sqlText!=""){
              for(let i=0;i<obj.length;i++){
                let layers = obj[i].subLayers.layers;
                for(let j=0;j<layers.length;j++){
                  layers[j].displayFilter = sqlText;//SQL查询过滤
                }
              }
            }
            that.postTempLayersSet(index,layerUrl,zIndex,obj);//创建并获取超图临时图层
          }
        }
      };
    },
    postTempLayersSet(index,layerUrl,zIndex,obj){//创建并获取超图临时图层
      let that = this;
      let url = encodeURI(layerUrl+"/tempLayersSet.rjson");
      let entry = JSON.stringify(obj);
      let xhr = new XMLHttpRequest();//第一步：建立所需的对象
      xhr.open("POST", url, true);//第二步：打开连接  将请求参数写在url中
      xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
      //获取数据后的处理程序
      xhr.onreadystatechange = function(){
        let readyState = xhr.readyState;
        if (readyState == 4){
          let status = xhr.status;
          let responseText =  xhr.responseText ;
          let result = JSON.parse(responseText);
          if(result.succeed){
            let layerID = result.newResourceID;
            let newResourceLocation = result.newResourceLocation;
            //that.$message({ message: '创建临时图层成功!', type: 'success' });
            //查询超图临时图层
            //that.getMapTempLayer(index,layerUrl,layerID,zIndex);
            //根据layerUrl、临时图层layerID和zIndex查询并添加瓦片地图图层REST
            that.createMapRestLayer(index,layerUrl,layerID,zIndex);
          }else{
            //that.$message({ message: '创建临时图层失败!', type: 'warning' });
          }
          xhr.onreadystatechange = function(){};
          xhr = null;
        }
      };
      xhr.send(entry);//第三步：发送请求  将请求参数写在URL中
    },
    getMapTempLayer(index,layerUrl,layerID,zIndex){//查询超图临时图层
      let that = this;
      let url = encodeURI(layerUrl + "/tempLayersSet.rjson");
      //查询
      let httpRequest = new XMLHttpRequest();//第一步：建立所需的对象
      httpRequest.open('GET', url, true);//第二步：打开连接  将请求参数写在url中  ps:"http://localhost:8080/rest/xxx"
      httpRequest.send();//第三步：发送请求  将请求参数写在URL中
      //获取数据后的处理程序
      httpRequest.onreadystatechange = function () {
        if (httpRequest.readyState == 4 && httpRequest.status == 200) {
          let json = httpRequest.responseText;//获取到json字符串，还需解析
          let obj = JSON.parse(json);
          if(obj.length>0){
            if(layerID!=null && layerID!=""){
              for(let i=0;i<obj.length;i++){
                if(obj[i].name==layerID){
                  //根据layerUrl、临时图层layerID和zIndex查询并添加瓦片地图图层REST
                  that.createMapRestLayer(index,layerUrl,layerID,zIndex);
                  break;
                }
              }
            }else{
              layerID  = obj[0].name;//默认取第一个
              //根据layerUrl、临时图层layerID和zIndex查询并添加瓦片地图图层REST
              that.createMapRestLayer(index,layerUrl,layerID,zIndex);
            }
            that.$message({ message: '查询成功!', type: 'success' });
          }else{
            that.$message({ message: '无查询结果!', type: 'warning' });
          }
        }
      };
    },
    queryTempLayersSetBySql(index,layerUrl,zIndex,sqlText) {//根据SQL条件筛选更新并查询超图临时图层信息
      let that = this;
      let url = encodeURI(layerUrl + "/tempLayersSet.rjson");
      //查询
      let httpRequest = new XMLHttpRequest();
      httpRequest.open('GET', url, true);
      httpRequest.send();
      //获取数据后的处理程序
      httpRequest.onreadystatechange = function () {
        if (httpRequest.readyState == 4 && httpRequest.status == 200) {
          let json = httpRequest.responseText;//获取到json字符串，还需解析
          let obj = JSON.parse(json);
          if(obj.length>0){
            //let tempUrl = obj[0].path;
            let layerID  = obj[0].name;//默认选第一个临时图层
            //更新超图临时图层信息
            that.getPutTempLayersSet(index,layerUrl,layerID,zIndex,sqlText);
          }
        }
      };
    },
    getPutTempLayersSet(index,layerUrl,layerID,zIndex,sqlText){//更新超图临时图层信息
      let that = this;
      //查询
      let url = encodeURI(layerUrl+"/tempLayersSet/"+layerID+".rjson");
      //查询
      let httpRequest = new XMLHttpRequest();//第一步：建立所需的对象
      httpRequest.open('GET', url, true);//第二步：打开连接  将请求参数写在url中  ps:"http://localhost:8080/rest/xxx"
      httpRequest.send();//第三步：发送请求  将请求参数写在URL中
      //获取数据后的处理程序
      httpRequest.onreadystatechange = function () {
        if (httpRequest.readyState == 4 && httpRequest.status == 200) {
          let json = httpRequest.responseText;//获取到json字符串，还需解析
          let obj = JSON.parse(json);
          if(obj.length>0){
            for(let i=0;i<obj.length;i++){
              let layers = obj[i].subLayers.layers;
              for(let j=0;j<layers.length;j++){
                layers[j].displayFilter = sqlText;//SQL查询过滤
              }
            }
          }
          //更新超图临时图层信息
          that.putTempLayersSet(index,url,layerUrl,layerID,zIndex,obj);
        }
      };
    },
    putTempLayersSet(index,url,layerUrl,layerID,zIndex,obj){//更新超图临时图层信息，获取临时图层
      let that = this;
      let entry = JSON.stringify(obj);
      let xhr = new XMLHttpRequest();//第一步：建立所需的对象
      xhr.open("PUT", url, true);//第二步：打开连接  将请求参数写在url中
      xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
      //获取数据后的处理程序
      xhr.onreadystatechange = function(){
        let readyState = xhr.readyState;
        if (readyState == 4){
          let status = xhr.status;
          let responseText =  xhr.responseText ;
          let result = JSON.parse(responseText);
          if(result.succeed){
            //that.$message({ message: '更新临时图层成功!', type: 'success' });
            //查询超图临时图层
            //that.getMapTempLayer(index,layerUrl,layerID,zIndex);
            //根据layerUrl、临时图层layerID和zIndex查询并添加瓦片地图图层REST
            that.createMapRestLayer(index,layerUrl,layerID,zIndex);
          }else{
            //that.$message({ message: '更新临时图层失败!', type: 'warning' });
          }
          xhr.onreadystatechange = function(){};
          xhr = null;
        }
      };
      xhr.send(entry);//第三步：发送请求  将请求参数写在URL中
    },
    //初始化全部图层数据类型数组
    initAllRestLayers(array){
      if(array && array.length>0){
        for(let i=0;i<array.length;i++){
          let code = array[i].code;
          let name = array[i].name;
          let sqlText = array[i].sqlText;
          let obj = {
            code:code,//图层序号
            name:name,//图层名称
            vectorTileLayer:null,//REST矢量切片图层
            restTileLayer:null,//REST瓦片图层
            sqlText:sqlText,//查询条件
            tempLayerId:null,//临时图层ID
            vectorTileStyles:null,//矢量切片样式
          };
          //REST图层
          this.restLayerArray.push(obj);
          let layerName = array[i].url.split("/rest/maps/")[1];
          //图层名称数组
          this.allLayerNameArray.push(layerName);
        }
      }
    },
    //根据查询图层信息参数查询并显示图层
    queryLayersByParams(params){
      if(params.code && params.code!=="" && params.name && params.name!==""){
        //清空全部选择图层要素
        this.clearAllSelectionLayer();
        for(let i=0;i<this.restLayerArray.length;i++){
          if(this.restLayerArray[i].code===params.code){
            if(this.restLayerArray[i].vectorTileLayer!=null){//REST矢量切片图层
              //移除图层
              this.map.removeLayer(this.restLayerArray[i].vectorTileLayer);
              this.restLayerArray[i].vectorTileLayer = null;
              this.restLayerArray[i].vectorTileStyles = null;
            }
            if(this.restLayerArray[i].restTileLayer!=null){//REST瓦片图层
              //移除图层
              this.map.removeLayer(this.restLayerArray[i].restTileLayer);
              this.restLayerArray[i].restTileLayer = null;
            }
            //地图服务
            let url = this.dataTypeInfoArray[i].url;
            console.log(url);
            //test
            //url = "http://10.13.155.192:8090/iserver/services/map-fxfzypg/rest/maps/district_boundary_province@fxfzypg";

            if(params.show) {//显示图层
              let zIndex = this.dataTypeInfoArray[i].zIndex;
              let sqlText = params.sqlText;
              console.log(sqlText);
              if(sqlText && sqlText!==""){//根据sql条件显示临时图层
                let layerID = this.restLayerArray[i].tempLayerId;//临时图层ID
                if(layerID!=null && layerID!=="") {//指定临时图层ID
                  //更新超图临时图层信息
                  this.getPutTempLayersSet(i,url,layerID,zIndex,sqlText);
                }else{
                  this.createRestMapTempLayersSet(i,url,zIndex,sqlText);//查询REST图层信息并创建新的临时图层
                }
                //根据url和zIndex、sqlText添加矢量切片图层
                // this.createVectorTileLayer(i,url,zIndex,sqlText);
              }else{//显示整个图层
                // this.deleteRestMapTempLayersSet(url,null);//删除超图临时图层
                // url = "http://10.13.155.192:8090/iserver/services/map-fxfzypg/rest/maps/district_boundary_china@fxfzypg";
                //根据url、临时图层layerID和zIndex添加瓦片地图图层REST
                this.createMapRestLayer(i,url,'',zIndex);
                //根据url和zIndex添加矢量切片图层
                // this.createVectorTileLayer(i,url,zIndex,null);
              }
            }else{//隐藏图层
              //
            }

            break;
          }
        }
      }
    },
    getLayerLegend(realName,layerUrl,bbox){//根据url获取图层图例信息
      let that = this;
      layerUrl += '/legend.json?bbox='+bbox;
      layerUrl += '&returnVisibleOnly=false';//是否只返回当前地图范围内可见要素的图例。默认为 false
      //图层图例信息查询
      let httpRequest = new XMLHttpRequest();//第一步：建立所需的对象
      httpRequest.open('GET', layerUrl, true);//第二步：打开连接  将请求参数写在url中  ps:"http://localhost:8080/rest/xxx"
      httpRequest.send();//第三步：发送请求  将请求参数写在URL中
      /**
       * 获取数据后的处理程序
       */
      httpRequest.onreadystatechange = function () {
        if (httpRequest.readyState == 4 && httpRequest.status == 200) {
          let json = httpRequest.responseText;//获取到json字符串，还需解析
          let obj = JSON.parse(json);
          let layerLegends = obj.layerLegends;
          debugger
          if(layerLegends!=null && layerLegends.length>0){
            let html = '';
            for(let i=0;i<layerLegends.length;i++){
              let layerLegend = layerLegends[i];
              //获取图层名称
              let layerName = layerLegend.layerCaption;
              if(layerName.indexOf("#")!=-1){//文字图层
                continue;
              }
              layerName = realName;
              let legends = layerLegend.legends;
              if(legends!=null && legends.length>0){
                if(legends.length>1){//多图例图层
                  html += '<p style="text-align: center;font-weight: bold;">'+layerName+'</p>';
                  for(let j=0;j<legends.length;j++){
                    let legend = legends[j];
                    let values = legend.values;
                    if(values==null){
                      continue;
                    }
                    let imageData = legend.imageData;
                    let contentType = legend.contentType;
                    let url = legend.url;
                    let label = legend.label;
                    let width = legend.width;
                    let height = legend.height;
                    let imgSrc = "data:image/jpeg;base64,"+imageData;
                    //html += '<p style="height: 16px;">';
                    //html += '<p>';
                    html += '<p style="height: '+height+'px;">';
                    html += '<img style="width:'+width+'px;height:'+height+'px" src="'+imgSrc+'" />';
                    html += '<span style="top: -2px;left: 10px;height: 16px;font-size: 16px;">'+label+'</span>';
                    html += '</p>';
                  }
                }else{//单一图例图层
                  let legend = legends[0];
                  let values = legend.values;
                  let imageData = legend.imageData;
                  let contentType = legend.contentType;
                  let url = legend.url;
                  let label = legend.label;
                  let width = legend.width;
                  let height = legend.height;
                  let imgSrc = "data:image/jpeg;base64,"+imageData;
                  //html += '<p style="height: 16px;">';
                  //html += '<p>';
                  html += '<p style="height: '+height+'px;">';
                  html += '<img style="width:'+width+'px;height:'+height+'px" src="'+imgSrc+'" />';
                  html += '<span style="position: relative;top: -2px;left: 10px;height: 16px;font-size: 16px;">'+layerName+'</span>';
                  html += '</p>';
                }
              }
            }
            //图例html
            that.$emit("getLegendHtml",{name:realName,legendHtml:html});
          }
        }
      };
    },
    //清除全部图层
    clearAllLayers(){
      if(this.map && this.restLayerArray && this.restLayerArray.length>0){
        //清空全部选择图层要素
        this.clearAllSelectionLayer();
        for(let i=0;i<this.restLayerArray.length;i++) {
          if (this.restLayerArray[i].vectorTileLayer != null) {//REST矢量切片图层
            //移除图层
            this.map.removeLayer(this.restLayerArray[i].vectorTileLayer);
            this.restLayerArray[i].vectorTileLayer = null;
            this.restLayerArray[i].vectorTileStyles = null;
          }
          if(this.restLayerArray[i].restTileLayer!=null){//REST瓦片图层
            //移除图层
            this.map.removeLayer(this.restLayerArray[i].restTileLayer);
            this.restLayerArray[i].restTileLayer = null;
          }
        }
        this.$emit("finishClearAll",true);
      }
    },
    //显示全部图层
    showAllLayers(){
      this.clearAllLayers();//清除全部图层
      if(this.map && this.dataTypeInfoArray && this.dataTypeInfoArray.length>0){
        for(let i=0;i<this.dataTypeInfoArray.length;i++){
          let obj = this.dataTypeInfoArray[i];
          if(i==0){
            //显示全部图层showAllLayersBool=true
            //根据url和zIndex添加矢量切片图层
            // this.createVectorTileLayer(0,obj.url,obj.zIndex,obj.sqlText);
          }
          //根据url、临时图层layerID和zIndex添加瓦片地图图层REST
          this.createMapRestLayer(i,obj.url,'',obj.zIndex);
        }
      }
    },
    //根据url和zIndex、sqlText添加矢量切片图层
    createVectorTileLayer(index,layerUrl,zIndex,sqlText) {
      let that = this;
      //layerUrl = "http://10.13.155.192:8090/iserver/services/map-fxfzypg/rest/maps/district_boundary_china@fxfzypg";
      //瓦片地图图层
      let mapService = new MapService(layerUrl);//根据超图矢量瓦片图层获取图层信息
      mapService.getMapInfo(function (serviceResult) {
        if(serviceResult.result!=undefined){
          let mapJSONObj = serviceResult.result;
          //获取超图发布的REST图层
          //let options = TileSuperMapRest.optionsFromMapJSON(newUrl, mapJSONObj);
          let layerName = mapJSONObj.name;//图层名称
          //获取图层范围
          let bounds = mapJSONObj.bounds;
          let left = bounds.left;
          let bottom = bounds.bottom;
          let right = bounds.right;
          let top = bounds.top;
          let origin = [left, top];//左上角
          let extent = [left, bottom, right, top];//图层范围
          //获取超图发布的REST矢量切片图层（自定义比例尺）
          let resultArr = getVectorTileLayer(that.map,layerUrl,origin,extent,that.map.getView(),mapJSONObj,sqlText,0);
          let layer = resultArr[0];
          that.restLayerArray[index].vectorTileStyles = resultArr[1];//矢量切片样式
          //自定义样式
          that.restLayerArray[index].vectorTileStyles.setCustomStyleFuntion(that.customStylesObj);
          that.map.addLayer(layer);
          zIndex = zIndex - 1;//test
          //设置图层叠加顺序
          layer.setZIndex(zIndex);
          //添加到REST图层数组
          that.restLayerArray[index].vectorTileLayer = layer;
          // console.log("extent");
          // console.log(extent);
          //缩放到图层范围
          that.map.getView().fit(extent, {padding: [50, 50, 50, 50]});
          //图层范围
          let bbox = extent.join(",");
          //图层显示名称
          let realName = that.restLayerArray[index].name;
          //获取图例
          that.getLayerLegend(realName,layerUrl,bbox);//根据url获取图层图例信息

          //显示全部图层
          if(that.showAllLayersBool==true){
            let nextIndex = index + 1;//下一个图层序号
            if(nextIndex<that.dataTypeInfoArray.length){
              let obj = that.dataTypeInfoArray[nextIndex];
              setTimeout(function(){
                //根据url和zIndex添加矢量切片图层
                // that.createVectorTileLayer(nextIndex,obj.url,obj.zIndex,obj.sqlText);
              },1000);
            }else{
              that.$emit("finishShowAll",true);
            }
          }
        }
      });
    },
    //清空全部选择图层要素
    clearAllSelectionLayer(){
      let index = this.selectLayerIndex;
      if(index!=null && this.restLayerArray[index].vectorTileLayer){
        //矢量切片样式
        if(this.restLayerArray[index].vectorTileStyles){
          this.restLayerArray[index].vectorTileStyles.featureSelectedFunction({
            selectedId: null,
            layerName: null,
            fieldId:null
          });
          this.selectLayerIndex = index;
          if(this.restLayerArray[index].vectorTileLayer){
            this.restLayerArray[index].vectorTileLayer.changed();
          }
        }
      }
    },
    changeAllLayersCustomStyle(){//更新图层自定义样式
      if(this.restLayerArray!=null && this.restLayerArray.length>0){
        for(let i=0;i<this.restLayerArray.length;i++){
          if(this.restLayerArray[i].vectorTileStyles){
            this.restLayerArray[i].vectorTileStyles.setCustomStyleFuntion(this.customStylesObj);
          }
          if(this.restLayerArray[i].vectorTileLayer){
            this.restLayerArray[i].vectorTileLayer.changed();
          }
        }
      }
    },
  }
}

</script>

<style scoped>

</style>